//
//  MixViewController.m
//  Jyxt
//
//  Created by 刘日 on 17/5/17.
//  Copyright © 2017年 DaLian Rental Housing Management. All rights reserved.
//

#import "MixViewController.h"
#import <Masonry.h>
#import "BubbleMixCom.h"
#import "UserCenterViewModel.h"

@interface MixViewController ()

@property (nonatomic , strong) BubbleMixCom *Bubble;

@end

@implementation MixViewController

- (BubbleMixCom *)Bubble{
    if (!_Bubble) {
        _Bubble = [BubbleMixCom new];
    }
    return _Bubble;
}

- (void)initView{
    self.title = @"加载中...";
    self.view.backgroundColor = [UIColor whiteColor];
    self.lkNavigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemRefresh target: self action: @selector(refresh)];
    self.mixView = [[LemonMixView alloc] init];
    [self.view addSubview: self.mixView];
    self.mixView.frame = CGRectMake(0, 64, LK_SIZE_SCREEN_WIDTH, LK_SIZE_SCREEN_HEIGHT - 64);
    __block MixViewController *_s = self;
    [self.mixView.on addOnLoadCompleteCallback:^(LemonMixView *mixView) {
        [_s.mixView.data getTitle:^(LemonMixView *mixView, NSString *strResult) {
            _s.title = [strResult isEqualToString: @""] ? @"加载中..." : strResult;
        }];
        [_s.mixView.operate evaluateJavaScript: [NSString stringWithFormat: @"ComTool.putToken('%@')" , [UserCenterViewModel getLocalUToken]] complete:^(id  _Nullable result, NSError * _Nullable error) {
            
        }];
    }];
    [self.mixView.on addOnLoadProgressChangeCallback:^(LemonMixView *mixView, double progress) {
        _s.progressView.hidden = progress >= 1;
        if (progress < 1) {
            _s.title = @"加载中...";
        }
        _s.progressView.progress = progress;
    }];
    __block MixViewController *sf = self;
    [self.mixView.on addOnReceiveJSMsgCallback:^(LemonMixView *mixView, NSDictionary *msg) {
        @try {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
            [[sf valueForKey: msg[@"clazz"]] performSelector: NSSelectorFromString([NSString stringWithFormat: @"%@:" , msg[@"method"]]) withObject: msg[@"data"]];
#pragma clang diagnostic pop
        } @catch (NSException *exception) {
            NSLog(@"LemonMix内部发生严重错误：无法执行指定的方法！%@" , exception);
        } @finally {
            
        }
    }];
    
    if (_url) {
        [self.mixView.operate loadUrl: _url];
    }
}

- (UIProgressView *)progressView{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 64, LK_SIZE_SCREEN_WIDTH, 20)];
        [self.view addSubview: _progressView];
    }
    return _progressView;
}

- (void)setUrl:(NSString *)url{
    self->_url = url;
    if (self.mixView) {
        [self.mixView.operate loadUrl: url];
    }
}

- (void)refresh{
    [self.mixView.operate reload];
}

@end
